package com.study.controller;

import com.study.utils.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

@Controller
@Slf4j
public class UploadController {

    @Value("${file.path}")
    private String filePath;

    @RequestMapping("/")
    public String index(Model model) {

        // 获取访问量信息
        String txtFilePath = "D://logs//count.txt";
        Long count = Get_Visit_Count(txtFilePath);
        System.out.println(count);
        model.addAttribute("count", count); // 后台参数传递给前端

        return "index";
    }

    @RequestMapping("/multi")
    public String multi(Model model) {
        return "multiFile";
    }

    /**
     * 单文件上传
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload1")
    @ResponseBody
    public Map<String, String> upload1(@RequestParam("file") MultipartFile file)
            throws IOException {
        log.info("[文件类型] - [{}]", file.getContentType());
        log.info("[文件名称] - [{}]", file.getOriginalFilename());
        log.info("[文件大小] - [{}]", file.getSize());
        file.transferTo(new File(filePath + file.getOriginalFilename()));
        Map<String, String> result = new HashMap<>(16);
        result.put("contentType", file.getContentType());
        result.put("fileName", file.getOriginalFilename());
        result.put("fileSize", file.getSize() + "");
        return result;
    }

    //多文件上传和单文件，在前端的区别只是在input标签中是否加上 multiple 标记而已

    @PostMapping("/multipleFiles")
    @ResponseBody
    public String multipleFiles(@RequestParam("file") MultipartFile[] files, HttpServletRequest request) {
        //List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        if (null == files && files.length == 0) {
            return null;
        }

        for (MultipartFile mf : files) {
            //文件名称
            String filename = mf.getOriginalFilename();
            if (mf.isEmpty()) {
                return "文件名称：" + filename + "上传失败，原因是文件为空!";
            }
            File dir = new File(filePath + filename);

            try {
                //写入文件
                mf.transferTo(dir);
                log.info("文件名称：" + filename + "上传成功");
            } catch (IOException e) {
                log.error(e.toString(), e);
                return "文件名称：" + filename + "上传失败";
            }
        }
        return "多文件上传成功";
    }

    @RequestMapping(value = "/uploadDir", method = RequestMethod.POST)
    @ResponseBody
    public String upload(@RequestParam("dir") MultipartFile[] dir) {
        System.out.println("上传文件夹...");
        File file;
        String fileName = "";
        String filePath = "";
        for (MultipartFile f : dir) {
            fileName = f.getOriginalFilename();
            String type = f.getContentType();
            System.out.println("\n" + fileName + " ," + type);
            filePath = "D:\\logs\\" + fileName.substring(0, fileName.lastIndexOf("/"));
            if (!FileUtil.isDir(filePath)) {
                FileUtil.makeDirs(filePath);
            }
            file = new File("D:\\logs\\" + fileName);
            try {
                file.createNewFile();
                //将上传文件保存到一个目标文件中
                f.transferTo(file);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "filelist";
    }

    /*
     * 获取txt文件中的数字，即之前的访问量
     * 传入参数为： 字符串: txtFilePath,文件的绝对路径
     */
    public static Long Get_Visit_Count(String txtFilePath) {

        try {
            //读取文件(字符流)
            BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(txtFilePath), "UTF-8"));
            //循环读取数据
            String str = null;
            StringBuffer content = new StringBuffer();
            while ((str = in.readLine()) != null) {
                content.append(str);
            }
            //关闭流
            in.close();

            //System.out.println(content);
            // 解析获取的数据
            Long count = Long.valueOf(content.toString());
            count++; // 访问量加1
            //写入相应的文件
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(txtFilePath), "UTF-8"));
            out.write(String.valueOf(count));

            //清楚缓存
            out.flush();
            //关闭流
            out.close();

            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0L;
        }
    }
}
